import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from '@/utils/request'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('admin_token') || '')
  const username = ref('')

  function setToken(newToken) {
    token.value = newToken
    localStorage.setItem('admin_token', newToken)
    if (newToken) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
    }
  }

  function logout() {
    token.value = ''
    username.value = ''
    localStorage.removeItem('admin_token')
    delete axios.defaults.headers.common['Authorization']
  }

  // 初始化时设置 token
  if (token.value) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
  }

  return {
    token,
    username,
    setToken,
    logout
  }
})

